<template>
  <div class="faq-container">
    <!-- 顶部标题 -->
    <van-nav-bar
        title="系统常见问题"
        left-text="返回"
        right-text="更多问题"
        @click-left="router.push('/personal')"
        @click-right="showAllQuestions"/>
    <!-- 分类标签 -->
    <van-tabs v-model:active="activeCategory" swipeable @change="onChangeTab">
      <van-tab
          v-for="category in categories"
          :key="category.id"
          :title="category.name"
          :name="category.id"
          v-model:active="active"
      >
        <!-- 问题列表 -->
        <van-cell
            v-for="faq in faqs"
            :key="faq.id"
            :title="faq.question"
            is-link
            @click="showFaqDetail(faq)"
        />
      </van-tab>
    </van-tabs>
    <!-- 底部按钮 -->
    <div class="footer-buttons">
      <van-button round type="primary" icon="comment" @click="showFeedback">意见反馈</van-button>
      <van-button round color="#ccc" icon="service" @click="contactCustomerService">客服助手</van-button>
    </div>
    <!-- 问题详情弹窗 -->
    <van-dialog
        v-model:show="showDialog"
        :title="currentFaq?.question"
        show-cancel-button
        cancel-button-text="关闭"
        confirm-button-text=""
        class="faq-dialog"
    >
      <div class="dialog-content">
        <div class="answer" v-html="formatAnswer(currentFaq?.answer || '')"></div>
        <div class="action-buttons">
          <van-button
              round
              size="small"
              icon="flower-o"
              :color="liked ? '#ff566b' : ''"
              @click="handleLike"
          >{{ currentFaq?.likeNum || 0 }}
          </van-button>
          <van-button
              round
              size="small"
              :color="disliked ? '#2d6dd4' : ''"
              @click="handleDislike"
          >
            <span class="iconfont">&#xe64b;</span>
            {{ currentFaq?.uselessNum || 0 }}
          </van-button>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import {showToast, showFailToast, Icon} from 'vant'
import type {API} from "@/type/type";
import {listFaqCategoryAPI} from "@/api/faq/faqCategory";
import {useRouter} from 'vue-router';
import {pageFaqAPI, updateFaqAPI} from "@/api/faq/faq";

// 响应式数据
const categories = ref<API.IFaqCategory[]>([])
const faqs = ref<API.IFaq[]>([])
const activeCategory = ref<number>(1)
const showDialog = ref(false)
const currentFaq = ref<API.IFaq | null>(null)
const liked = ref(false)
const disliked = ref(false)
const router = useRouter()
const active = ref("all");

const fetchFaqCategories = async () => {
  const {data} = await listFaqCategoryAPI({});
  if (!data) {
    categories.value = [{id: "all", name: '常见问题', sortOrder: 1, status: '1'} as any]
  }
  const categoryData = data.map((item) => {
    return {
      id: item.id,
      name: item.name,
      sortOrder: item.sortOrder,
      status: item.status
    }
  })
  categories.value = [{id: "all", name: '常见问题', sortOrder: 1, status: '1'} as any, ...categoryData]
}

const fetchFaqs = async (name = 'all') => {
  const {data} = await pageFaqAPI({
    pageSize: 100,
    current: 1,
    categoryId: name === 'all' ? '' : name
  })
  faqs.value = data.data
}

const onChangeTab = async (name: string) => {
  await fetchFaqs(name)
}

// 方法
const showAllQuestions = () => {
  showToast('暂未实现更多问题')
}

const showFaqDetail = (faq: API.IFaq) => {
  currentFaq.value = faq
  showDialog.value = true
  // 重置点赞状态
  liked.value = false
  disliked.value = false
}

const formatAnswer = (answer: string) => {
  return answer.replace(/\n/g, '<br>')
}
// 点赞功能
const handleLike = async () => {
  if (!currentFaq.value) return

  if (liked.value) {
    currentFaq.value.likeNum = currentFaq.value.likeNum ? currentFaq.value.likeNum - 1 : 0
    liked.value = false
  } else {
    currentFaq.value.likeNum = currentFaq.value.likeNum ? currentFaq.value.likeNum + 1 : 1
    liked.value = true
    if (disliked.value) {
      currentFaq.value.uselessNum = currentFaq.value.uselessNum ? currentFaq.value.uselessNum - 1 : 0
      disliked.value = false
    }
  }
  await updateFaqAPI({
    id: currentFaq.value.id,
    likeNum: currentFaq.value.likeNum,
    uselessNum: currentFaq.value.uselessNum
  })
}

const handleDislike = async () => {
  if (!currentFaq.value) return
  if (disliked.value) {
    currentFaq.value.uselessNum = currentFaq.value.uselessNum ? currentFaq.value.uselessNum - 1 : 0
    disliked.value = false
  } else {
    currentFaq.value.uselessNum = currentFaq.value.uselessNum ? currentFaq.value.uselessNum + 1 : 1
    disliked.value = true
    if (liked.value) {
      currentFaq.value.likeNum = currentFaq.value.likeNum ? currentFaq.value.likeNum - 1 : 0
      liked.value = false
    }
  }
  await updateFaqAPI({
    id: currentFaq.value.id,
    likeNum: currentFaq.value.likeNum,
    uselessNum: currentFaq.value.uselessNum
  })
}

const showFeedback = () => {
  showToast('跳转意见反馈页面')
}

const contactCustomerService = () => {
  showToast('联系客服助手')
}

// 生命周期
onMounted(async () => {
  try {
    await fetchFaqCategories()
    await fetchFaqs()
  } catch (error) {
    showFailToast('加载数据失败')
  }
})
</script>

<style scoped>
.faq-container {
  padding-bottom: 60px;
}

.footer-buttons {
  position: fixed;
  bottom: 10px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  padding: 0 16px;
  z-index: 100;
}

:deep(.van-tab__pane) {
  padding-bottom: 60px;
}

.faq-dialog {
  max-width: 90%;
}

.dialog-content {
  padding: 16px;
}

.answer {
  margin-bottom: 20px;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}
</style>
